package com.meihua.baoleyi.fragment.sickness;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.base.BaseFragment;
import com.meihua.baoleyi.bean.CurePlanBean;
import com.meihua.baoleyi.bean.WXPayBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.ui.MyOrderActivity;
import com.meihua.baoleyi.utils.IsPayPasswordUtil;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.widget.AlertDialog;
import com.meihua.baoleyi.widget.CustomerKeyboard;
import com.meihua.baoleyi.widget.PasswordEditText;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by jzm on 2017/11/11.
 * zm.jin@qq.com
 */

public class TherapCureFragment1 extends BaseFragment implements CustomerKeyboard.CustomerKeyboardClickListener, PasswordEditText.PasswordFullListener {

    @Bind(R.id.webView)
    WebView webview;
    @Bind(R.id.loading)
    ProgressBar mLoading;
    private Context mcontext;
    private CurePlanBean bean;
    private boolean mhidden;

    public static TherapCureFragment1 newInstance(String url) {
        TherapCureFragment1 fragment = new TherapCureFragment1();
        Bundle mBundle = new Bundle();
        mBundle.putString("json", url);
        fragment.setArguments(mBundle);
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mcontext = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.therap_fragment1, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    /**
     * 初始化数据
     */
    private void initView() {
        String json = getArguments().getString("json");
        bean = NetHelper.getBeanForJson(CurePlanBean.class, json);
        webview.addJavascriptInterface(new AndroidToJs(), "android");
        showWebView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            mhidden = false;
        } else {
            mhidden = true;
        }
    }

    /**
     * 加载H5页面
     */
    private void showWebView() {
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        settings.setDefaultTextEncodingName("utf-8");
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);

        // 设置允许JS弹窗
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (null == mLoading) return;
                if (newProgress < 100) {
                    mLoading.setProgress(newProgress);
                } else {
                    mLoading.setVisibility(View.GONE);
                }
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        //携带数据请求
        webview.loadUrl(APIServer.GOODSDETAIL + MyApp.getInstance().getToken() + "/" + MyApp.getInstance().getUser_id() + "/" + bean.getData().getGoods_id());
    }

    /*以下三个方法是输入支付密码弹框*/
    @Override
    public void click(String numder) {
        passwordEditText.addPassword(numder);
    }

    @Override
    public void delete() {
        passwordEditText.deleteLastPassword();
    }

    @Override
    public void passwordFull(final String password) {
        getServerData(mStatus, mID, password);
        dialog.dismiss();
    }

    private String mStatus;
    private String mID;

    /**
     * 请求数据
     *
     * @param status
     * @param id
     */
    private void getServerData(final String status, String id, String pwd) {
        /*验证支付密码*/
        TreeMap<String, String> params = new TreeMap<String, String>();
        params.put("user_id", MyApp.getInstance().getUser_id());
        params.put("order_id", id);
        params.put("status", status);
        params.put("pay_password", pwd);
        NetHelper.post(APIServer.ORDERPAY, params, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                /*请求得到的数据*/
                WXPayBean bean = NetHelper.getBeanForJson(WXPayBean.class, s);
                if (bean != null) {
                    if (status.equals("1")) {
                        wxPay(bean);
                    } else if (status.equals("2")) {
                        if (bean.getCode().equals("200")) {
                            startActivity(new Intent(getActivity(), MyOrderActivity.class));
                        }
                        //余额支付
                        Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }


    /*js调用Android*/
    class AndroidToJs {
        /*支付*/
        @JavascriptInterface
        public void go_pay(String status, String id, String num) {
            mStatus = status;
            mID = id;
            if (status.equals("1")) {//微信支付
                getServerData(status, id, "");
            } else if (status.equals("2")) {//余额支付
                //判断是否设置了支付密码
                IsPayPasswordUtil.isPayPassword(getActivity(), new IsPayPasswordUtil.OnIsPayPassword() {
                    @Override
                    public void isSetPayPassword(boolean isSet) {
                        if (isSet) {
                            //弹出输入密码对话框
                            showCustomInputDialog();
                        }
                    }
                });
            } else {//银行卡支付
                ToastUtil.show(getActivity(), "银行卡服务暂时没有开通");
            }
        }

        /*关闭界面*/
        @JavascriptInterface
        public void closeWeb() {
//            CommonWebActivity.this.finish();
        }

    }

    /*微信支付*/
    private void wxPay(WXPayBean wx) {
        try {
            if (wx.getCode().equals("1")) {
                //调用微信支付
                IWXAPI mWxApi = WXAPIFactory.createWXAPI(getActivity(), wx.getData().getAppid(), true);
                mWxApi.registerApp(wx.getData().getAppid());
                PayReq req = new PayReq();
                req.appId = wx.getData().getAppid();// 微信开放平台审核通过的应用APPID
                req.partnerId = wx.getData().getMch_id();// 微信支付分配的商户号
                req.prepayId = wx.getData().getPrepay_id();// 预支付订单号，app服务器调用“统一下单”接口获取
                req.packageValue = "Sign=WXPay";// 固定值Sign=WXPay，可以直接写死，服务器返回的也是这个固定值
                req.nonceStr = wx.getData().getNonce_str();// 随机字符串，不长于32位，服务器小哥会给咱生成
                req.timeStamp = wx.getData().getTimestamp() + "";// 时间戳，app服务器小哥给出
                req.sign = wx.getData().getSign();// 签名，服务器小哥给出，他会根据：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3指导得到这个
                mWxApi.sendReq(req);
            } else {
                Toast.makeText(getActivity(), "添加失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private PasswordEditText passwordEditText;
    private CustomerKeyboard mCustomerKeyboard;
    private AlertDialog dialog;

    /*弹出输入密码对话框*/
    private void showCustomInputDialog() {

        //弹出dialog输入框
        dialog = new AlertDialog.Builder(getActivity()).
                setContentView(R.layout.activity_password).
                fullWith().
                setCancelable(true).
                formBottom(true).
                show();
        passwordEditText = dialog.getView(R.id.password);
        mCustomerKeyboard = dialog.getView(R.id.customer_keyboard);
        mCustomerKeyboard.setOnCustomerKeyboardClickListener(this);
        passwordEditText.setEnabled(false);
        passwordEditText.setOnPasswordFullListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(getActivity());
    }

    public WebView getWebview() {
        return webview;
    }

    public void setWebview(WebView webview) {
        this.webview = webview;
    }

    public boolean isMhidden() {
        return mhidden;
    }

    public void setMhidden(boolean mhidden) {
        this.mhidden = mhidden;
    }
}
